package com.java2007.hotel.controller.front;

import com.alibaba.druid.support.json.JSONWriter;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.java2007.hotel.constant.ServletConstant;
import com.java2007.hotel.controller.Controller;
import com.java2007.hotel.entity.DinnerCar;
import com.java2007.hotel.pojo.User;
import com.java2007.hotel.service.DinnerCarService;
import com.java2007.hotel.service.impl.DinnerCarServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Reckeys
 * @version V1.0
 * @date 2021/01/27
 **/
@WebServlet("/dinnercar")
public class DinnerCarController extends Controller {
    private DinnerCarService dinnerCarService = new DinnerCarServiceImpl();


    /**
     * 添加商品到购物车
     * 如果数量小于等于0，则删除数据
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String addFoodToDinnerCar(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //判断用户是否登陆,未登录不允许下单
        Object user = request.getSession().getAttribute("user");
        if (user == null){
            return ServletConstant.jump("请先登陆","user/login.jsp");
        }

        String foodIdStr = request.getParameter("foodId");
        String numberStr = request.getParameter("number");
        //判断传来的值是否为空
        if (StringUtils.isEmpty(foodIdStr) || StringUtils.isEmpty(numberStr)) {
            return "菜的信息错误！";
        }

        //从session域中获取购物车列表，如果不存在则创建
        HttpSession session = request.getSession();
        List<DinnerCar> dinnerCarList = (List<DinnerCar>) session.getAttribute("dinnerCarList");
        if (null == dinnerCarList) {
            dinnerCarList = new ArrayList<>();
        }

        Integer foodId = Integer.valueOf(foodIdStr);
        Integer number = Integer.valueOf(numberStr);
        //将菜和数量 添加到购物车
        List<DinnerCar> dinnerCarListNew = dinnerCarService.addFoodToDinnerCar(foodId, number, dinnerCarList);

        //计算总金额
        Long totalPrice = 0L;
        for (DinnerCar dinnerCar : dinnerCarList) {
            totalPrice = totalPrice + dinnerCar.getDetailTotalPrice();
        }

        //将购物车内的信息保存到session域
        session.setAttribute("dinnerCarList", dinnerCarListNew);
        session.setAttribute("totalPrice", totalPrice);

        return "redirect:/front/detail/clientCart.jsp";
    }

    /**
     * 删除购物车内的商品
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("AlibabaCollectionInitShouldAssignCapacity")
    public String deleteFoodToDinnerCar(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取传入的值
        String foodIdStr = request.getParameter("foodId");

        //从session域中获取菜单信息和总金额
        HttpSession session = request.getSession();
        List<DinnerCar> dinnerCarList = (List<DinnerCar>) session.getAttribute("dinnerCarList");
        Long totalPrice = (Long) session.getAttribute("totalPrice");

        //判断购物车是否为空
        if (dinnerCarList == null || "".equals(foodIdStr)) {
            return "没有东西可以删除";
        }

        Integer foodId = Integer.valueOf(foodIdStr);

        //用于判断是否删除
        boolean flag = false;

        // 遍历查找相同的菜id
        for (DinnerCar dinnerCar : dinnerCarList) {
            if (dinnerCar.getDetailFoodId().intValue() == foodId.intValue()) {
                totalPrice = totalPrice - dinnerCar.getDetailTotalPrice();
                dinnerCarList.remove(dinnerCar);
                flag = true;
                break;
            }
        }

        //noinspection AlibabaCollectionInitShouldAssignCapacity
        Map<String, Object> map = new HashMap<>(16);

        //如果删除了，修改session域中的信息
        if (flag) {
            session.setAttribute("dinnerCarList", dinnerCarList);
            session.setAttribute("totalPrice", totalPrice);
            map.put("tprice", totalPrice);
            map.put("success", true);
            return JSON.toJSONString(map);
        }
        return null;
    }

    /**
     * 修改购物车内的菜的数量
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String updateDinnerCar(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String foodIdStr = request.getParameter("foodId");
        String numberStr = request.getParameter("number");

        //判断传来的值是否为空
        if (StringUtils.isEmpty(foodIdStr)) {
            return "菜的信息错误！";
        }

        //从session域中获取菜单信息和总金额
        HttpSession session = request.getSession();
        List<DinnerCar> dinnerCarList = (List<DinnerCar>) session.getAttribute("dinnerCarList");
        Long totalPrice = (Long) session.getAttribute("totalPrice");

        Integer foodId = Integer.valueOf(foodIdStr);

        Integer number = null;

        //判断数量是否合法，不合法着返回
        try {
            number = Integer.valueOf(numberStr);
        } catch (NumberFormatException e) {
            Map<String,Object> map = new HashMap<>(16);
            map.put("success",false);
            return JSON.toJSONString(map);
        }
        if (number <= 0) {
            Map<String,Object> map = new HashMap<>(16);
            map.put("success",false);
            return JSON.toJSONString(map);
        }

        //用于判断是否修改
        boolean flag = false;
        long detailTotalPrice = 0L;
        //遍历查询菜id相同的数据
        for (DinnerCar dinnerCar : dinnerCarList) {
            if (dinnerCar.getDetailFoodId().intValue() == foodId.intValue()) {
                dinnerCar.setDetailNumber(number);
                dinnerCar.setDetailTotalPrice(number * dinnerCar.getDetailPrice());
                detailTotalPrice = dinnerCar.getDetailTotalPrice();
                flag = true;
                break;
            }
        }

        //如果修改这更新总金额
        if (flag) {
            totalPrice = 0L;
            for (DinnerCar dinnerCar : dinnerCarList) {
                totalPrice = totalPrice + dinnerCar.getDetailTotalPrice();
            }
            //将修改后的信息重新写入到session域中
            session.setAttribute("dinnerCarList",dinnerCarList);
            session.setAttribute("totalPrice", totalPrice);

            Map<String,Object> map = new HashMap<>(16);
            map.put("success",true);
            map.put("totalPrice",totalPrice);
            map.put("detailTotalPrice",detailTotalPrice);
            return JSON.toJSONString(map);
        }
        return null;

    }


}